package cn.microservices.cloud.common.web.handlers;

import cn.microservices.cloud.common.core.exceptions.BusinessException;
import cn.microservices.cloud.common.core.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 参数 异常统一处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * service 手动抛出异常
     *
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public Response handleValidationExceptions(BusinessException ex) {
        //单个参数校验
        String exMessage = ex.getMessage();
        log.error("参数异常 = {}", exMessage);

        return Response.errorMsg(exMessage);
    }


    /**
     * 参数异常校验 统一返回200 使用内部code 处理
     *
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleValidationExceptions(MethodArgumentNotValidException ex) {

        //单个参数校验
        String exMessage = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数异常 = {}", exMessage);

        return Response.errorMsg(exMessage);

//多参数校验
//        JSONObject errors = new JSONObject();
//        ex.getBindingResult().getAllErrors().forEach((error) -> {
//            String fieldName = ((FieldError) error).getField();
//            String errorMessage = error.getDefaultMessage();
//            errors.put(fieldName, errorMessage);
//        });
//
//        log.error("参数异常 = {}",errors);
//        return Response.errorMsg(errors.toJSONString());
    }


    /**
     * 缺少请求体异常处理器
     *
     * @param e 缺少请求体异常
     * @return ResponseResult
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        log.error("缺少参数请求体");
        String msg = "缺少请求参数";
        return Response.errorMsg(msg);
    }
}